package com.dzt.androidframework.jsoup.detail.model;

import android.os.AsyncTask;
import android.util.Log;

import com.dzt.androidframework.jsoup.detail.bean.ImageDetailDomain;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by M02323 on 2017/7/12.
 */

public class RemoteDetailDataSource implements DetailDataSource {
	private onImageDetailParseListener listener;

	private RemoteDetailDataSource() {
	}

	private static class SingletonHolder {
		static RemoteDetailDataSource sInstance = new RemoteDetailDataSource();
	}

	public static RemoteDetailDataSource getInstance() {
		return RemoteDetailDataSource.SingletonHolder.sInstance;
	}

	public void init() {
	}

	@Override
	public void getImageDetail(String url, onImageDetailParseListener listener) {
		this.listener = listener;
		new getImageDetailTask().execute(url);
	}

	/*
   * 解析网页数据
   * */
	private class getImageDetailTask extends AsyncTask<String, List<ImageDetailDomain>, List<ImageDetailDomain>> {
		private String mArticle;

		@Override
		protected List<ImageDetailDomain> doInBackground(String... params) {
			List<ImageDetailDomain> imageDetailDomains = new ArrayList<>();
			Document doc = null;
			try {
				doc = Jsoup.connect(params[0]).get();

			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				doc.charset(Charset.forName("gb2312"));
				//图片
				Elements elementsImage = doc.getElementsByClass("scroll-item");
				//图片描述
				Element elementsImageDesc = doc.getElementById("imageTextDesc");
				Elements elementsByTag = elementsImageDesc.getElementsByTag("p");
				//循环得到图片列表和图片描述
				for (int i = 0; i < elementsByTag.size(); i++) {
					String imageDesc = elementsByTag.get(i).text();
					String imageUrl = elementsImage.get(i).getElementsByTag("img").first().attr("src");
					imageDetailDomains.add(new ImageDetailDomain(imageUrl, imageDesc));
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			try {
				//文章
				Element elementarticle = doc.getElementsByClass("article").first();
				mArticle = elementarticle.toString();
			} catch (Exception e) {
				mArticle = "<center>没有发现相关文章,试试图集吧！</center>";
			}
			return imageDetailDomains;
		}

		@Override
		protected void onPostExecute(List<ImageDetailDomain> ImageDetailDomainList) {
			if (null == ImageDetailDomainList || ImageDetailDomainList.size() == 0) {
				listener.onFailed("加载数据失败");
			} else {
				listener.onSuccess(ImageDetailDomainList, mArticle);
				Log.e("RemoteDetailDataSource", "加载数据成功");
			}
			super.onPostExecute(ImageDetailDomainList);
		}
	}
}
